package org.rslai.tcedit.web.user;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.security.SecurityUtil;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 修改用户密码
 * 
 * @author rslai
 * 
 * @spring.bean name="/user/password.jspx"
 */
public class PasswordController extends AbstractMvcController {

    @Override
    public Map getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String message = "";
        String username = SecurityUtil.getCurrentUsername();
        Map<String, String> map = new HashMap<String, String>();

        if(request.getMethod().equals("POST")) {
            String oldPassword = HttpUtil.getString(request, "oldPassword");
            String newPassword = HttpUtil.getString(request, "newPassword");
            try {
                userService.changePassword(username, oldPassword, newPassword);
                message = "口令已成功更改！";
            }
			catch (Exception e) {
				map.put("error", convertException(e));
			}
        }
        map.put("username", username);
        map.put("message", message);
        return map;
    }

    @Override
    public String getView(HttpServletRequest request, HttpServletResponse response) {
        return "/user/password.htm";
    }

    private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

}
